<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="productSearch" class="demo-form-inline">
        <!--条件查询-->
        <el-form-item>
          <el-input v-model="productSearch.prodName" placeholder="货品名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="productSearch.price" placeholder="货品价格"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="productSearch.catId" placeholder="所属种类">
            <el-option label="所有种类" value="0"></el-option>
            <el-option :label="c.catName" :value="c.catId" v-for="c in categoryList" :key="c.catId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addProduct">添加货品</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="productList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="货品ID"
            align="center"
            prop="prodId"
            width="180"/>
        <el-table-column
            label="货品名称"
            align="center"
            prop="prodName"
        />
        <el-table-column
            label="价格"
            align="center"
            prop="price"
        />
        <el-table-column
            label="数量"
            align="center"
            prop="quantity"
        />
        <el-table-column
            label="描述"
            align="center"
            prop="description"
        />
        <el-table-column
            label="所属种类"
            align="center"
            prop="catId"
        />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页导航面板-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!--编辑添加和修改货品对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="product" :rules="rules" ref="ruleForm">
        <el-form-item label="货品名称" prop="PROD_NAME" :label-width="formLabelWidth">
          <el-input v-model="product.prodName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="PRICE" :label-width="formLabelWidth">
          <el-input v-model.number="product.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="QUANTITY" :label-width="formLabelWidth">
          <el-input v-model.number="product.quantity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="DESCRIPTION" :label-width="formLabelWidth">
          <el-input v-model="product.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属种类" prop="CAT_ID" :label-width="formLabelWidth">
          <el-select v-model="product.catId" placeholder="请选择所属种类">
            <el-option label="所有种类" value="0"></el-option>
            <el-option :label="c.catName" :value="c.catId" v-for="c in categoryList" :key="c.catId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProduct">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import productApi from "@/api/product"
import categoryApi from "@/api/category"

export default {
  data() {
    // 自定义校验规则
    let checkPrice = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('价格不能为空'))
      } else if (isNaN(value)) {
        return callback(new Error('价格必须为数字值'))
      } else if (value < 0) {
        return callback(new Error('价格必须大于0'))
      } else {
        callback()
      }
    }

    return {
      productList: [],
      page: 1,        // 当前面
      pageSize: 5,    // 每页显示记录条数
      total: 100,     // 总记录数
      productSearch: {}, // 查询条件对象
      categoryList: [],   // 所有种类
      dialogFormVisible: false, // 对话框显示状态
      product: {},  // 代表修改货品对象
      title: '添加货品',
      formLabelWidth: '100px',  // 表单标签宽度
      multipleSelection: [],     // 代表选中的多项
      pids: [],                  // 代表删除的货品编号数组

      // 定义校验规则
      rules: {
        prodName: [
          { required: true, message: '请输入货品名称', trigger: 'blur' },
        ],
        price: [
          { validator: checkPrice, trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字值', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
        ],
        catId: [
          { required: true, message: '请选择所属种类', trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    this.search()
    this.findAllCategories()
    // this.findProducts()
  },
  methods: {
    // 查询所有货品
    async findProducts() {
      const { data: res } = await productApi.findAllProducts()
      if (res.code === 200) {
        this.productList = res.data.list
        console.log(this.productList)
      }
    },
    // 分页查询
    async findByPage() {
      const { data: res } = await productApi.findByPage(this.page, this.pageSize)
      console.log(res)
      if (res.code === 200) {
        this.productList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 查询所有种类
    async findAllCategories() {
      const { data: res } = await categoryApi.findAllCategories()
      if (res.code === 200) {
        this.categoryList = res.data.list
      }
    },
    // 条件查询带分页
    async search() {
      const { data: res } = await productApi.search(this.page, this.pageSize, this.productSearch)
      console.log(1,res)
      if (res.code === 200) {
        console.log(2,res.data.pr.rows)

        this.productList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    // 添加货品
    addProduct() {
      // 修改对话框标题
      this.title = "添加货品"
      // 清空原来的数据
      this.product = {}
      // 打开对话框
      this.dialogFormVisible = true
    },
    // 保存货品
    saveProduct() {
      this.$refs.ruleForm.validate(async valid => {
        //
        let url = "/product/add"
        let method = "post"
        if (this.product.prodId) {
          url = "/product/update"
          method = "put"
        }
        // 向后端发送请求,执行添加或修改货品
        if (valid) {
          const { data: res } = await productApi.save(url, method, this.product)
          console.log("res:", res)
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: res.message,
              onClose: () => {
                // 关闭对话框
                this.dialogFormVisible = false
                // 重新查询
                this.search()
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }
        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    // 当pagesize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      // this.findByPage()
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val

      this.search()
      console.log(`当前页: ${val}`);
    },
    // 编辑货品
    handleEdit(index, row) {
      // 修改对话框标题
      this.title = '修改货品'
      // 显示要修改的货品信息到对话框
      this.product = row
      // 打开对话框
      this.dialogFormVisible = true

      console.log(index, row);
    },
    // 删除货品
    handleDelete(index, row) {
      this.pids = [];
      if (row) {
        this.pids.push(row.prodId)
      } else {
        this.pids = this.multipleSelection.map(m => m.prodId)
      }
      this.$confirm(`删除货品ID为${this.pids}的货品`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        productApi.deleteProduct(this.pids)
            .then(({ data: res }) => {
              console.log("res:", res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    // 重新加载数据
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>
<style>
#app{
  display: flex;
  justify-content: center;
}
.el-card{
  width: 90%;
}
.el-pagination{
  margin: 20px;
  text-align: right;
}
</style>
